//
// Created on 2025/10/16.
//
// Node APIs are not fully supported. To solve the compilation error of the interface cannot be found,
// please include "napi/native_api.h".

#ifndef MINDSPORE_LITE_THREAD_SAFE_QUEUE_H
#define MINDSPORE_LITE_THREAD_SAFE_QUEUE_H
#include <queue>
#include <mutex>
template <typename T> class ThreadSafeQueue {
private:
    std::queue<T> queue_;
    mutable std::mutex mutex_;
    std::condition_variable cond_;

public:
    ThreadSafeQueue() = default;
    ~ThreadSafeQueue() = default;

    // 禁止拷贝（安全考虑）
    ThreadSafeQueue(const ThreadSafeQueue&) = delete;
    ThreadSafeQueue& operator=(const ThreadSafeQueue&) = delete;

    // 入队操作（支持移动语义）
    void enqueue(T value) {
        {
            std::lock_guard<std::mutex> lock(mutex_);
            queue_.push(std::move(value));
        }
        cond_.notify_one();  // 通知等待的消费者
    }

    // 出队操作（阻塞直到有数据）
    T dequeue() {
        std::unique_lock<std::mutex> lock(mutex_);
        // 避免虚假唤醒：队列空时持续等待
        cond_.wait(lock, [this] { return !queue_.empty(); });
        
        T value = std::move(queue_.front());
        queue_.pop();
        return value;
    }
    
    // 安全检查队列是否为空
    bool empty() const {
        std::lock_guard<std::mutex> lock(mutex_);
        return queue_.empty();
    }

    // 获取队列大小
    size_t size() const {
        std::lock_guard<std::mutex> lock(mutex_);
        return queue_.size();
    }
    
};

#endif //MINDSPORE_LITE_THREAD_SAFE_QUEUE_H
